package com.wrx.club_management_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wrx.club_management_backend.common.AjaxResult;
import com.wrx.club_management_backend.entity.AllocationNotice;
import com.wrx.club_management_backend.entity.AllocationRequest;
import com.wrx.club_management_backend.mapper.AllocationNoticeMapper;
import com.wrx.club_management_backend.mapper.AllocationRequestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.codec.json.AbstractJackson2Decoder;
import org.springframework.remoting.jaxws.AbstractJaxWsServiceExporter;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/finance")
public class FinanceController {

    @Autowired
    AllocationNoticeMapper allocationNoticeMapper;

    @Autowired
    AllocationRequestMapper allocationRequestMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    // 创建批款通知
    @PostMapping("/create_notice")
    public AjaxResult createFinanceAllocationNotice(@RequestBody AllocationNotice allocationNotice){
        int insert = allocationNoticeMapper.insert(allocationNotice);
        return AjaxResult.success("创建成功", allocationNotice.getId());
    }

    @PostMapping("/list_notice")
    public AjaxResult list_notice(){
        List<AllocationNotice> noticeList = allocationNoticeMapper.selectList(null);
        noticeList.stream().forEach(item -> {
            List<AllocationRequest> requestList = new ArrayList<>(
                    allocationRequestMapper.selectList(
                            new LambdaQueryWrapper<AllocationRequest>()
                                    .eq(AllocationRequest::getAllocationNoticeId, item.getId())
                    )
            );
            item.setList(requestList);
        });
        return AjaxResult.success(noticeList);
    }

    // 根据 id 查询批款通知
    @PostMapping("/getNoticeByNoticeId/{allocationNoticeId}")
    public AjaxResult listNotice(@PathVariable("allocationNoticeId")Long allocationNoticeId){
        AllocationNotice allocationNotice = allocationNoticeMapper.selectById(allocationNoticeId);
        List<AllocationRequest> list = new ArrayList<>(allocationRequestMapper.selectList(
                new LambdaUpdateWrapper<AllocationRequest>()
                        .eq(AllocationRequest::getAllocationNoticeId, allocationNoticeId)
        ));
        allocationNotice.setList(list);
        return AjaxResult.success(allocationNotice);
    }

    // 根据社团id 查询批款通知
    @PostMapping("/getNoticeByClubId/{clubId}")
    public  AjaxResult listNoticeByClubId(@PathVariable("clubId") Long clubId){
        List<AllocationNotice> noticeList = allocationNoticeMapper.selectList(
                new LambdaQueryWrapper<AllocationNotice>()
                        .eq(AllocationNotice::getClubId, clubId)
        );
        return AjaxResult.success(noticeList);
    }

    @PostMapping("/getRequestByNoticeId/{NoticeId}")
    public AjaxResult getRequestByNoticeId(@PathVariable("NoticeId") Long NoticeId){
        List<AllocationRequest> list = allocationRequestMapper.selectList(
                new LambdaQueryWrapper<AllocationRequest>()
                        .eq(AllocationRequest::getAllocationNoticeId, NoticeId)
        );
        return AjaxResult.success(list);
    }

    @PostMapping("/getRequestNoAllocationId")
    public AjaxResult getRequestNoAllocationId() {
        List<AllocationRequest> requests = allocationRequestMapper.selectList(
                new LambdaQueryWrapper<AllocationRequest>()
                        .isNull(AllocationRequest::getAllocationNoticeId)
                        .orderByDesc(AllocationRequest::getCreateTime)
        );

        return AjaxResult.success(requests);
    }



    // 创建批款申请
    @PostMapping("/create_request")
    public AjaxResult createFinanceAllocationRequest(@RequestBody AllocationRequest allocationRequest){
        int insert = allocationRequestMapper.insert(allocationRequest);
        return AjaxResult.success("创建成功");
    }


    // 修改批款通知状态
    @PostMapping("/completion/{allocationNoticeId}")
    public AjaxResult  completion(@PathVariable("allocationNoticeId") Long allocationNoticeId){
        allocationNoticeMapper.completion(allocationNoticeId);
        return AjaxResult.success("结项成功");
    }

    // 创建批款申请
    @PostMapping("/create_allocation_request")
    public AjaxResult createAllocationRequest(@RequestBody AllocationRequest allocationRequest){
        allocationRequestMapper.insert(allocationRequest);
        return AjaxResult.success("申请发送成功");
    }

    // 修改批款申请状态
    @PostMapping("update_allocation_request/{requestId}/{stat}")
    public AjaxResult updateAllocationRequest(
            @PathVariable("requestId") Long requestId,
            @PathVariable("stat") int stat
    ){
        //TODO 如果stat == 1 就给该社团打钱
        AllocationRequest request = allocationRequestMapper.selectById(requestId);
        String key = "club:fund:" + request.getClubId();
        Object o =  stringRedisTemplate.opsForHash().get(key, request.getTags());
        Long amount = 0L;
        if(o != null)  amount = Long.parseLong((String) o);
        amount = amount ==null? 0 : amount;
        amount += request.getAmount();
        stringRedisTemplate.opsForHash().put(key, request.getTags(), amount.toString());
        allocationRequestMapper.updateStatus(requestId, stat);
        return AjaxResult.success("修改状态成功");
    }

    @PostMapping("/totalBalance/{clubId}")
    public AjaxResult totalBalance(@PathVariable("clubId") Long clubId){
        String key = "club:fund:" + clubId;
        Long sum = 0L;
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(key);
        for (Object map_key : map.keySet()) {
            sum += Long.parseLong( map.get(map_key).toString());
        }
        map.put(0, sum.toString());
        return AjaxResult.success(map);
    }

    @PostMapping("/getRequestNumByStat/{clubId}/{stat}")
    public AjaxResult getRequestNumByStat(@PathVariable("clubId") Long clubId,@PathVariable("stat") int stat){
        Integer count = allocationRequestMapper.selectCount(
                new LambdaQueryWrapper<AllocationRequest>()
                        .eq(AllocationRequest::getClubId, clubId)
                        .eq(AllocationRequest::getStat, stat)
        );
        return AjaxResult.success(count);
    }

    @PostMapping("/updateRequestNoticeId/{noticeId}/{requestId}")
    public AjaxResult updateRequestNoticeId(@PathVariable("noticeId") Long noticeId, @PathVariable("requestId") Long requestId){
       allocationRequestMapper.updateNoticeId(noticeId, requestId);
       return AjaxResult.success("更新成功");
    }


}
